#include <stdio.h>
#include <stdlib.h>

typedef struct stack {
    int *data;
    int ptr;
    int size;
} STACK;

STACK *init(int size)
{
    STACK *stack = malloc(sizeof(STACK));
    stack->ptr = 0;
    stack->size = size;
    stack->data = (int *) calloc(size, sizeof(int));
    return stack;
}

void push(STACK *stack, int val)
{
    if(stack->ptr >= stack->size) {
        stack->size = stack->size * 3 / 2;
        stack->data = (int *) realloc(stack->data, stack->size * sizeof(*stack->data));
    }
    stack->data[stack->ptr++] = val;
}

void pop(STACK *stack)
{
    if(stack->size > stack->ptr*2) {
        stack->size = stack->size/2;
        stack->data = realloc(stack->data, stack->size * sizeof(*stack->data));        
    }   
    stack->ptr--;    
}

void print(STACK *stack)
{
    int counter = 0;
    while(counter < stack->ptr) {
        printf("%d ", stack->data[counter++]);
    }
    printf("\n");
}

int main()
{
    STACK *stack = init(5);

    printf("Size: %d\n", stack->size);
    printf("Actual size: %lu\n", sizeof(stack->data)/sizeof(stack->data[0]));

    push(stack, 12);
    push(stack, 2);
    push(stack, 22);
    print(stack);
    push(stack, 23);
    push(stack, 7);
    push(stack, 11);
    print(stack);
    pop(stack);
    print(stack);
    pop(stack);
    pop(stack);
    pop(stack);
    print(stack);

    printf("Size: %d\n", stack->size);
    printf("Actual size: %lu\n", sizeof(stack->data)/sizeof(stack->data[0]));

    return 0;
}